﻿#region NameSpace
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Eb.StockManagement;
using Eb.MessageBox;
#endregion

public partial class Procure : System.Web.UI.UserControl
{
    #region Fields
    StockManagement stockManagement = new StockManagement();
    static double grdTotal = 0;
    static int PID ;
    static int purchaseorderNumber = 0;
    static int purchaseType = 0;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            GetOrderDetails();
        }
    }

    #region Methods
    protected void GetOrderDetails()
    {
        DataSet orderDS = stockManagement.GetPurchaseOrderDetails();
        if (orderDS.Tables[0].Rows.Count > 0)
        {
            FromPurchase.Visible = true;
            mccbMasterItems.DataSource = orderDS.Tables[0];
            mccbMasterItems.DataBind();
        }
        else
        {
            lblMsg.Text = "No Items Found";
            FromPurchase.Visible = false;

        }
    }
    #endregion

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.mccbMasterItems.RowSelectionChanged += new ExtendedWebComboBox.MultiColumnComboBox.OnIntellisenseRowSelect(this.mccbMasterItems_RowSelectionChanged);

    }
    #endregion

    #region Events
    protected void mccbMasterItems_RowSelectionChanged(LinkButton sender, ExtendedWebComboBox.SelectedRowEventArgs args)
    {
        if (args.Cells[1].ToString() == "General")
        {
            purchaseType = 2;
        }
        else
        {
            purchaseType = 1;
        }

        int PurchaseOrderId = 0;
        if (args.Cells[0].ToString() != null)
            PurchaseOrderId = Convert.ToInt16(args.Cells[0].ToString());
        purchaseorderNumber = PurchaseOrderId;
        if (purchaseType == 1)
        {
           
            DataSet orderDS = stockManagement.GetPurchaseOrderData(PurchaseOrderId);
            if (orderDS.Tables[0].Rows.Count > 0)
            {
                pnlGeneral.Visible = false;
                PID = 0;
                Panel1.Visible = true;
                txtProductName.Text = orderDS.Tables[0].Rows[0]["ProductName"].ToString();
                lblProductCode.Text = orderDS.Tables[0].Rows[0]["ProductCode"].ToString();
                lblAmount.Text = orderDS.Tables[0].Rows[0]["PR_ApproximateAmount"].ToString();
                lblProductQty.Text = orderDS.Tables[0].Rows[0]["PR_ProductQuantity"].ToString();
                int productID = Convert.ToInt32(orderDS.Tables[0].Rows[0]["ProductID"].ToString());
                PID = productID;
                DataSet materialDS = stockManagement.GetMaterialByProductID(productID);
                grvMaterial.DataSource = materialDS;
                grvMaterial.DataBind();
            }
        }
        else
        {
            DataSet orderGeneralDS = stockManagement.GetGeneralPurchaseOrderByOrderIS(PurchaseOrderId);
            if (orderGeneralDS.Tables[0].Rows.Count > 0)
            {
                Panel1.Visible = false;
                lblDateOfCreation.Text = orderGeneralDS.Tables[0].Rows[0]["DateOfCreation"].ToString();
                lblApproxAmt.Text = orderGeneralDS.Tables[0].Rows[0]["PR_ApproximateAmount"].ToString();
                pnlGeneral.Visible = true;
                DataSet materialDS = stockManagement.GetGeneralPurchaseOrderMaterialByOrderID(PurchaseOrderId);
                grvPurchaseOrderGeneral.DataSource = materialDS;
                grvPurchaseOrderGeneral.DataBind();

            }
        }
    }
    protected void grvMaterial_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        double amt = 0;
        int uQty =0;
        double amount = 0;
        int qty = 0;
        //if (lblProductQty.Text.Trim() != "")
        //    uQty = Convert.ToInt32(lblProductQty.Text.Trim());
        //if (lblAmount.Text.Trim() != "")
        //    lblAmount.Text = Convert.ToInt32(lblAmount.Text);
        foreach (GridViewRow gvr in grvMaterial.Rows)
        {
            Label tbTotal = (Label)gvr.Cells[2].FindControl("txtTotal");
            Label price = (Label)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            int totQty = Convert.ToInt16(lblProductQty.Text);
            Label lblUnit = (Label)gvr.Cells[1].FindControl("lblStock");
            Label tbQty = (Label)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            qty = Convert.ToInt16(tbQty.Text);
            if (lblUnit.Text != "")
                uQty = Convert.ToInt16(lblUnit.Text);
            else
                uQty = 0;
            tbQty.Text = Convert.ToString(uQty * totQty);
            qty = Convert.ToInt16(tbQty.Text);
            amount = price1 * qty;
            //}
            tbTotal.Text = amount.ToString("C2");
            grdTotal = amount + amt;
            amt = grdTotal;

            string test = gvr.Cells[1].Text;
            //double ff=0;
            //string test = gvr.Cells[3].Text;
            //if(test!="")
            //     ff=Convert.ToDouble(test);
            //if (ff > 100)
            //    Response.Write("hi");


            //int totQty = Convert.ToInt16(txtQty.Text);
            ////if (int.TryParse(tbQty.Text.Trim(), out qty))
            ////{
            //qty = Convert.ToInt16(tbQty.Text);
            //if (lblUnit.Text != "")
            //    uQty = Convert.ToInt16(lblUnit.Text);
            //else
            //    uQty = 0;
            //tbQty.Text = Convert.ToString(uQty * totQty);
        }
    }
    protected void rbPurchaseOrder_CheckedChanged(object sender, EventArgs e)
    {
        if (rbPurchaseOrder.Checked)
        {
            GetOrderDetails();
            FromPurchase.Visible = true;
            Panel1.Visible = false;

        }
        else
        {
            FromPurchase.Visible = false;
            Panel1.Visible = false;
        }
    }
    protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (RadioButton1.Checked)
        {
            FromPurchase.Visible = false;
            Panel1.Visible = false;
        }
        else
        {
            FromPurchase.Visible = true;
            Panel1.Visible = false;
        }
    }
    protected void btnReceive_Click(object sender, EventArgs e)
    {

        ReceiveStock();
       // GetOrderDetails();

    }

    protected void ReceiveStock()
    {
        bool status1 = true;
        int uniqID  =0;
        int stock = 0;
        if (lblProductQty.Text.Trim() != "" || lblProductQty.Text.Trim() != null)
        {
            stock = Convert.ToInt16(lblProductQty.Text.Trim());

        }
        else
        {
            stock = 0;
        }
        int userId = 0;
        if (Session["UserId"] != null)
            userId = Convert.ToInt16(Session["UserId"].ToString());
        int productNo = PID;

        if (grvMaterial.Rows.Count > 0)
        {
            bool statuz = stockManagement.InsertProcureFromPurchase(purchaseorderNumber, txtReceiveDate.Text, txtRemerks.Text, purchaseType);
            uniqID = stockManagement.InsertMaterialBatchHistory(userId, productNo, 1);
            foreach (GridViewRow gvr in grvMaterial.Rows)
            {
                int materialQty=0;
                int materialId=0;
                Label lblMaterialID = (Label)gvr.Cells[0].FindControl("lblmaterialId");
                Label lblMaterialQty = (Label)gvr.Cells[2].FindControl("txtQuantity");
                if(lblMaterialID.Text!="" || lblMaterialID.Text!=null)
                    materialId=Convert.ToInt32(lblMaterialID.Text.Trim());
                else 
                    materialId=0;
                if(lblMaterialQty.Text!="" || lblMaterialQty.Text!=null)
                    materialQty=Convert.ToInt32(lblMaterialQty.Text.Trim());
                status1 = stockManagement.InsertMaterialHistory(uniqID, materialQty, materialId);
                if (status1)
                {
                    stockManagement.UpdateCurrentAvailabilityMaterialStock(materialId, materialQty,"");
                    stockManagement.UpdateMaterialStock1(materialId, materialQty);
                }
            }
            int intUniqID=stockManagement.GetRequestTypeIDByLinkKey(purchaseorderNumber,8);
            bool stockStatus= stockManagement.UpdateRequestListStatus(intUniqID, 5);
            if (stockStatus)
                MessageBox.Show("Successfully Added.");
            else
                MessageBox.Show("Failed to Add");
        }
        //if (purchaseType == 1)
        //{
        //    bool status = stockManagement.InsertProcureFromPurchase(purchaseorderNumber, txtReceiveDate.Text, txtRemerks.Text, purchaseType);
        //    bool batchHistoryStatus = stockManagement.InsertBatchHistory(productNo.ToString(), stock, 1, "", "", userId.ToString(), "", "", "");
        //    bool productStockStatus = stockManagement.UpdateCurrentAvailabilityOfStock(productNo, stock, "");
        //    bool productListStock = stockManagement.UpdateProductList(stock, productNo);
        //    UpdateRequestLinkStatus();
        //    MessageBox.Show("Successfully Added");

        //}
        //else
        //{
        //    bool status = stockManagement.InsertProcureFromPurchase(purchaseorderNumber, txtReceiveDate.Text, txtRemerks.Text, purchaseType);
        //    MessageBox.Show("Successfully Added");

        //}

    }
    #endregion
    protected void grvPurchaseOrderGeneral_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        double amt = 0;
        double amount = 0;
        foreach (GridViewRow gvr in grvPurchaseOrderGeneral.Rows)
        {
            Label price = (Label)gvr.Cells[3].FindControl("lblUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            Label lblRequiredQty = (Label)gvr.Cells[3].FindControl("lblReqQty");
            int qty = Convert.ToInt16(lblRequiredQty.Text);
            Label lblTotAmt = (Label)gvr.Cells[3].FindControl("lblTotAmt");
            amount = price1 * qty;
            lblTotAmt.Text = amount.ToString("C2");
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        bool status = stockManagement.InsertProcureFromPurchase(purchaseorderNumber, TextBox2.Text, TextBox1.Text, purchaseType);
        UpdateRequestLinkStatus();
        MessageBox.Show("Successfully Added");
        //GetOrderDetails();
    }

    protected bool UpdateRequestLinkStatus()
    {
         bool status;
       int RequestId = stockManagement.GetRequestTypeIDByLinkKey(purchaseorderNumber, 8);
       if (RequestId > 0)
           status = stockManagement.UpdateRequestListStatus(RequestId,5);
       else
           status = false;
       return status;
    }
}
